package pre.Work;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Exam02 implements Callable {
    @Override
    public Object call() throws Exception {
       return null;
    }
    //创建一个线程循环对一个数做加一操作，5秒后在主线程中中断线程并在主线程（main）输出结果。
    public static void main(String[] args) {
        Callable<Long> callable = new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                long i = 0;
                while (! Thread.currentThread().isInterrupted()) {
                    i++;
//                    try {
//                        Thread.sleep(10);
//                    }catch (InterruptedException e){
//                        Thread.currentThread().interrupt();
//                    }
                }
//                long num = 0;
//                while (true) {
//                    num++;
//                    if (Thread.interrupted()) { // true 已经被中断 false 是其他情况
//                        System.out.println("线程被中断了");
//                        System.out.println(num);
//                        break;
//                    }
//                }
                return i;
            }
        };
        FutureTask<Long> futureTask = new FutureTask<>(callable);
        FutureTask<Long> futureTask1 = new FutureTask<>(() ->{
            long sun = 0;
            while (true){
                sun ++;
                if (Thread.currentThread().isInterrupted()){
                    return sun;
                }
            }
        });
        Thread thread1 = new Thread(futureTask1);
        thread1.start();
        try {
            thread1.join(5000);
            thread1.interrupt();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            System.out.println(futureTask1.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }


//        Thread thread = new Thread(futureTask);
//        thread.start();
//
//        try {
//            Thread.sleep(5000);
//            thread.interrupt();
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        try {
//            System.out.println(futureTask.get());
//        } catch (InterruptedException | ExecutionException e) {
//            throw new RuntimeException(e);
//        }
    }
}
